package com.edu.controller.user;

import com.edu.dto.ResultDto;
import com.edu.entity.UserEntity;
import com.edu.service.UserService;
import com.edu.service.impl.UserServiceImpl;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

/**
 * 登录控制类，处理用户登录请求。
 * 通过继承HttpServlet类，实现对HTTP请求的处理。
 */
@WebServlet(urlPatterns = "/users/login")
public class LoginController extends HttpServlet {

    private UserService userService;

    /**
     * 初始化方法，用于实例化UserService。
     * 当Servlet被加载时调用此方法。
     */
    public LoginController() {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("loginGET");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String rst = ResultDto.success(null);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(rst);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UserEntity user = ServletHelper.getRequestBodyAsObject(request, UserEntity.class);
        String email = user.getEmail();
        String password = user.getPassword();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        Map<String, Object> resultMap = userService.login(email, password);
        response.setHeader("token", (String) resultMap.get("token"));
        if (resultMap != null) {
            String rst = ResultDto.success(resultMap);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(rst);
        } else {
            String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "登录失败。用户名或密码无效。");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(rst);
        }
    }
}
